<!--  -->
<template>
  <div class="page-container">
    <div class="header-panel">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="测站">
          <StbprpSelect v-model="queryParams.stcd" @change="stbprpChange" placeholder="请选择测站"></StbprpSelect>
        </el-form-item>

        <el-form-item label="曲线选择">
          <el-select v-model="queryParams.mstm" @change="mstmChange" placeholder="请选择" style="width: 100%;" clearable>
            <el-option v-for="item in mstmOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <!-- <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button> -->
          <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd"
            v-hasPermi="['sjcx:swkrgxqx:add']">新增</el-button>

          <el-button type="success" plain icon="el-icon-edit" :disabled="single" @click="handleUpdate"
            v-hasPermi="['sjcx:swkrgxqx:edit']">修改</el-button>

          <el-button type="danger" plain icon="el-icon-delete" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['sjcx:swkrgxqx:remove']">删除</el-button>
        </el-form-item>
      </el-form>

      <el-form :inline="true" :model="rightParams" class="demo-form-inline">
        <el-form-item>
          <el-row>
            <span>水位：</span><el-input v-model="inputRz" style="width: 100px;" placeholder="请输入内容"></el-input>
            <el-button type="primary" icon="el-icon-d-arrow-left" @click="convertRzW('1')" plain></el-button>
            <span style="color:brown;">转换</span>
            <el-button type="primary" style="margin-left: 0;" icon="el-icon-d-arrow-right" @click="convertRzW('2')"
              plain></el-button>
            <span>蓄水量：</span><el-input v-model="inputW" style="width: 100px;" placeholder="请输入内容"></el-input>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
    <div class="context-panel">
      <div class="context-left">
        <div class="chart" id="chart"></div>
      </div>
      <div class="context-right">
        <el-table :data="tableData" stripe style="width: 100%" v-el-table-infinite-scroll="loadMore" v-loading="loading"
          @selection-change="handleSelectionChange" height="calc(100% - 38px)">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="stcd" align="center" label="测站编码" />
          <el-table-column prop="mstm" align="center" label="时间" />
          <el-table-column prop="rz" align="center" label="库水位" />
          <el-table-column prop="w" align="center" label="蓄水量" />
        </el-table>
        <!-- 底部加载提示 -->
        <div class="load-more" v-if="tableData.length > 0">
          <span v-if="loading">加载中...</span>
          <span v-else-if="noMore">没有更多数据了</span>
          <span v-else>向下滚动加载更多</span>
        </div>
      </div>
    </div>



    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" :close-on-click-modal="false" append-to-body
      @close="dialogClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="测站编码" prop="stcd">
              <StbprpSelect v-model="form.stcd" placeholder="请选择测站" :disabled="isEdit" style="width: 100%;">
              </StbprpSelect>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="施测时间" prop="mstm">
              <el-date-picker v-model="form.mstm" type="datetime" :disabled="isEdit" placeholder="选择施测时间" value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="点序号" prop="ptno">
              <el-input v-model="form.ptno" type="number" :disabled="isEdit" placeholder="请输入点序号" />
            </el-form-item>
          </el-col>
           <el-col :span="12">
            <el-form-item label="水面面积" prop="wspa">
              <el-input v-model="form.wspa" type="number" placeholder="请输入水面面积（单位：km²）" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库水位" prop="rz">
              <el-input v-model="form.rz" type="number" placeholder="请输入库水位（单位：m）" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="蓄水量" prop="w">
              <el-input v-model="form.w" type="number" placeholder="请输入蓄水量（单位：10^4m³）" />
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import StbprpSelect from '@/components/Select/StbprpSelect'
import { calculateRZFromW, calculateWFromRZ } from '@/utils/calculate.js'
export default {
  components: { StbprpSelect },
  data() {
    return {
      queryParams: {
        tm: []
      },
      rightParams: {},
      allData: [],
      tableData: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      open: false,
      loading: false,
      page: 0,
      pageSize: 20,
      total: null,
      noMore: false,
      mstmOptions: [],
      mstmList: [],
      //转换
      inputRz: null,
      inputW: null,
      // 弹出层标题
      title: "",
      // 勾选元素
      selection: [],
      isEdit: false,
      // 表单参数
      form: {

      },
      dataList: [],
      open: false,
      // 表单校验
      rules: {
        stcd: [
          { required: true, message: '请选择测站编码', trigger: 'blur' },
        ],

      },
    }
  },
  computed: {},
  created() { },
  mounted() {

  },
  methods: {


    getMstmList() {
      this.$request({
        method: 'get',
        url: 'baseApi/st_zvarl_b/getMstmList',
        params: {
          // stcd: '11329410',
          stcd: this.queryParams.stcd
        }
      }).then((res) => {
        if (res.code === 200) {
          this.mstmOptions = res.data.map(item => {
            return {
              value: item.mstm,
              label: item.mstm
            }
          })
        }
      })
    },

    getList() {
      this.$request({
        method: 'get',
        url: 'baseApi/st_zvarl_b/getList',
        params: {
          stcd: this.queryParams.stcd,
          mstm: this.queryParams.mstm
        }
      }).then((res) => {
        if (res.code === 200) {
          const data = res.data
          this.allData = data
          this.total = data.length
          this.page = 1
          const count = Math.min(this.total, this.pageSize);
          this.tableData = data.slice(0, count)
          this.initChart()
        }
      })
    },

    handleQuery() {
      if (this.queryParams.stcd == null) {
        this.$message({
          message: '请选择站点',
          type: 'warning'
        });
        return
      };
      this.tableData = [];
      this.page = 0;
      this.noMore = false;
      this.getList();
    },

    // 加载更多数据
    async loadMore() {
      if (this.loading || this.noMore || this.page === 0) return;

      this.loading = true;
      try {
        await this.simulateRequest();
        const start = this.tableData.length;
        const remainingCount = this.total - start;
        const count = Math.min(this.pageSize, remainingCount);

        if (count <= 0) {
          this.noMore = true;
          return;
        }
        var newData = this.allData.slice(start, start + count)
        this.tableData = [...this.tableData, ...newData];

        if (this.tableData.length >= this.total) {
          this.noMore = true;
        }
      } catch (error) {
        console.error('加载更多数据失败:', error);
        this.$message.error('加载更多数据失败');
      } finally {
        this.loading = false;
      }
    },
    // 模拟请求延迟
    simulateRequest() {
      return new Promise(resolve => setTimeout(resolve, 800));
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    convertRzW(type) {
      if (this.allData.length == 0) {
        this.$message({
          message: '没有计算数据',
          type: 'warning'
        });
        return
      }
      if (type == '2') {
        // RZ转W
        const { w } = calculateWFromRZ(this.inputRz, this.allData)
        this.inputW = w
      } else if (type == '1') {
        // W转RZ
        const { rz } = calculateRZFromW(this.inputW, this.allData)
        this.inputRz = rz
      }
    },
    initChart() {
      var chartDom = document.getElementById('chart');
      var myChart = echarts.init(chartDom);
      const data = this.allData
      const rzw_data = data.map(item => [item.w, item.rz])
      const wMin = Math.floor(Math.min(...data.map(item => item.w)))
      const wMax = Math.ceil(Math.max(...data.map(item => item.w)))
      var option = {
        title: {
          text: '水位库容关系曲线',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            var vals = params[0].value
            return '水位:' + vals[1] + ' m<br/>蓄水量:' + vals[0] + ' 10<sup>6</sup>m³'
          }
        },
        grid: [
          {
            left: '5%',
            right: '6%',
            bottom: '6%',
            top: '8%'
          }
        ],
        xAxis: [
          {
            name: '蓄水量',
            axisTick: {
              alignWithLabel: true
            },
            splitLine: {
              show: false
            },
            type: 'value',
            min: wMin,
            max: wMax
          }
        ],
        yAxis: [
          {
            name: '水位(m)',
            type: 'value',
            axisLabel: {
              interval: 8,
              formatter: function (value, index) {
                return value
              }
            },
            splitLine: {
              show: false
            },
            scale: true,
            boundaryGap: [0.01, 0.01]
          }
        ],
        series: [
          {
            name: '库容关系曲线',
            type: 'line',
            color: '#7CB5EC',
            connectNulls: true,
            data: rzw_data,
            animation: true,
            animationDuration: 1500,
            // 填充区域的样式
            areaStyle: {
              normal: {
                // 填充色渐变
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#3aa7ff' },
                  { offset: 0.5, color: 'rgba(58, 167, 255,0.4)' },
                  { offset: 1, color: 'rgba(58, 167, 255,0)' }
                ])
              }
            }
          }
        ]
      };


      option && myChart.setOption(option);
    },
    stbprpChange(val) {
      this.getMstmList()
    },
    mstmChange() {
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.title = "添加信息";
      this.open = true
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.form = this.selection[0] || row
      this.isEdit = true
      this.title = "修改信息";
      this.open = true
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var ids;
      if (this.selection.length == 0) {
        ids = [row]
      } else {
        ids = this.selection
      }
      this.$confirm('是否确认删除该的数据项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$request({
          url: '/baseApi/st_zvarl_b/delete',
          method: 'post',
          data: ids
        })
          .then(res => {
            this.handleQuery();
            this.$message({
              message: '操作成功',
              type: 'success'
            });
          })

      }).catch(() => { })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let url = ''
          if (this.isEdit) {
            url = '/baseApi/st_zvarl_b/udpate'
          } else {
            url = '/baseApi/st_zvarl_b/insert'
          }
          this.$request({
            url: url,
            method: 'post',
            data: this.form
          }).then((res) => {
            if (res.code === 200) {
              this.open = false;
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.handleQuery()
            }
          })
        }
      });
    },
    resetForm() {
      this.isEdit = false
      this.$data.form = this.$options.data().form
      this.$refs.form && this.$refs.form.resetFields()
    },
    dialogClose() {
      this.isEdit = false
      this.resetForm()
    },


  },
}
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类样式
.header-panel {
  display: flex;
  justify-content: space-between;
}

.context-panel {
  display: flex;
  flex-direction: row;
  height: calc(100% - 50px);
  width: 100%;

  .context-left {
    flex: 5;
    border: 2px dashed #ddd;
  }

  .context-right {
    margin-left: 5px;
    flex: 3;
    overflow: hidden;
  }

  .chart {
    height: 100%;
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
  }
}

.load-more {
  text-align: center;
  padding: 10px;
  color: #1f4fec;
  font-size: 14px;
  background: #f8f9fa;
  border-top: 1px solid #ebeef5;
}
</style>